package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"tapi-go/global"
	"tapi-go/pkg/database"
	"tapi-go/pkg/logging"
	"tapi-go/pkg/setting"
	"tapi-go/routers"
	"time"
)

// @title gin服务测试
// @version 1.0
// @description 配置文件，日志文件，中间件，数据绑定，数据返回等
func main() {
	// 运行模式
	//gin.SetMode(gin.ReleaseMode)
	// 初始化Viper
	global.YY_VP = setting.Viper()
	// 初始化zap日志库
	global.YY_LOG = logging.Zap()
	// gorm连接数据库
	global.YY_DB = database.Gorm()
	// 初始化表
	database.MysqlTables(global.YY_DB)
	// 程序结束前关闭数据库链接
	db, _ := global.YY_DB.DB()
	defer db.Close()
	//启动程序
	RunWindowsServer()
}

type server interface {
	ListenAndServe() error
}

func RunWindowsServer() {
	Router := routers.InitRouters()
	address := fmt.Sprintf(":%d", global.YY_CONFIG.System.Addr)
	s := initServer(address, Router)
	// 保证文本顺序输出
	// In order to ensure that the text order output can be deleted
	time.Sleep(10 * time.Microsecond)
	global.YY_LOG.Info("server run success on 127.0.0.1", zap.String("port", address))
	global.YY_LOG.Error(s.ListenAndServe().Error())
}

func initServer(address string, router *gin.Engine) server {
	return &http.Server{
		Addr:           address,
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
}
